package com.axjy.cloud.weathe0309.service;


import com.axjy.cloud.weathe0309.vo.WeatherResponse;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationConfig;
import jdk.nashorn.internal.runtime.JSONFunctions;
import org.springframework.context.annotation.Bean;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.beans.Transient;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

@Service
public class WeatherServiceImpl implements WeatherService{

    @Resource
    private RestTemplate restTemplate;

    private static final String WEATHER_URI = "http://wthrcdn.etouch.cn/weather_mini?";

    @Override
    public WeatherResponse getDataByCityName(String cityName) {
        String url=WEATHER_URI+"city="+cityName;
        return getWeatherResponse(url);
    }

    @Override
    public WeatherResponse getDateByCityKey(String cityKey) {
        String url=WEATHER_URI+"citykey="+cityKey;
        return getWeatherResponse(url);
    }

    private WeatherResponse getWeatherResponse(String url) {
        System.out.println("执行了一次业务方法！");
        ResponseEntity<String> responseEntity= restTemplate.getForEntity(url,String.class);
        String str=responseEntity.getBody();
        System.out.println(str);
        ObjectMapper objectMapper=new ObjectMapper();
        WeatherResponse weatherResponse=null;
        try {
            weatherResponse=objectMapper.readValue(str,WeatherResponse.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return weatherResponse;
    }
}
